package day02;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * @author chenshijie
 * @date 2023/12/15 14:24
 */

public class NettyServer {
    public static void main(String[] args) {
        // 创建引导类ServerBootstrap，这个类将引导服务端的启动工作
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 创建两个NioEventLoopGroup类对象，可以看作传统IO编程模型的两大线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // 启动流程配置
        // 1. 通过group给引导类配置两个线程组，boss和worker
        // 2. 通过channel(NioServerSocketChannel.class)指定IO模型
        //      - NioServerSocketChannel NIO
        //      - OioServerSocketChannel BIO
        // 3. childHandler()方法，其创建了一个ChannelInitializer，定义后续每个连续的数据读写
        serverBootstrap
                .group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                System.out.println(msg);
                            }
                        });
                    }
                });
        bind(serverBootstrap, 8001);


    }

    private static void bind(final ServerBootstrap serverBootstrap, final int port) {
        serverBootstrap
                .bind(port)
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        if (future.isSuccess()) {
                            System.out.println("端口 ["+port+"] 绑定成功！");
                        } else {
                            System.out.println("端口 ["+port+"] 绑定失败！");
                            bind(serverBootstrap, port + 1);
                        }
                    }
                });
    }
}
